﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ForumsBrowser.ObjectGateway;
using System.Diagnostics;

namespace ForumsBrowser
{
    /// <summary>
    /// Interaction logic for ImageToken.xaml
    /// </summary>
    public partial class ImageToken : UserControl
    {
        public static readonly DependencyProperty ImageUrlProperty = 
            DependencyProperty.Register("ImageUrl", typeof(string), typeof(ImageToken), 
            new PropertyMetadata(string.Empty, OnPropertyChanged));

        public string ImageUrl
        {
            get { return (string)this.GetValue(ImageUrlProperty); }
            set { this.SetValue(ImageUrlProperty, value); }
        }

        public static void OnPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var token = (ImageToken)sender;
            var func = new Func<string, System.Drawing.Bitmap>(token.Convert);
            func.BeginInvoke(e.NewValue.ToString(), token.OnFileReceived, func);

        }

        public void OnFileReceived(IAsyncResult result)
        {

            var func = (Func<string, System.Drawing.Bitmap>)result.AsyncState;
            try
            {

                System.Drawing.Bitmap img = (System.Drawing.Bitmap)func.EndInvoke(result);
                image.Dispatcher.Invoke(new Action<System.Drawing.Bitmap>(
                i =>
                {
                    if (i != null)
                    {
                        System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                            i.GetHbitmap(),
                            IntPtr.Zero,
                            Int32Rect.Empty,
                            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                        image.Source = bitmapSource;
                    }
                }), img);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        public System.Drawing.Bitmap Convert(string url)
        {

            if (!string.IsNullOrEmpty(url))
            {
                System.Drawing.Bitmap image = (System.Drawing.Bitmap)Gateway.ImageGet(url);
                return image;
            }
            return null;
        }

        public ImageToken()
        {
            InitializeComponent();
        }
    }
}
